package Interfaces;

import SistemaCocheras.*;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JOptionPane;

/**
 *
 * @author Luciano
 */
public class marcarIngreso extends javax.swing.JFrame {

    private String dominio = "";
    private Connection conexion = null;
    private sistemaPrincipal sp = null;
    /** Creates new form marcarIngreso */

    public marcarIngreso() {
        initComponents();
        centrarJFrame();
    }

    
    public marcarIngreso(Connection c,sistemaPrincipal s) {
         initComponents();
         centrarJFrame();
         conexion = c;
         sp = s;
    }


    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        labelDominio = new javax.swing.JLabel();
        campoTextoDominio = new javax.swing.JTextField();
        botonAceptar = new javax.swing.JButton();
        botonCancelar = new javax.swing.JButton();
        checkBotonLugarP = new javax.swing.JCheckBox();
        campoTextoPosicion = new javax.swing.JTextField();
        tiposDeVehiculos = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("B&B - Ingreso de vehiculo");
        setResizable(false);

        labelDominio.setText("Dominio del Vehiculo(*):");

        botonAceptar.setText("Aceptar");
        botonAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonAceptarActionPerformed(evt);
            }
        });

        botonCancelar.setText("Cancelar");
        botonCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonCancelarActionPerformed(evt);
            }
        });

        checkBotonLugarP.setText(" Lugar Personalizado");
        checkBotonLugarP.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                checkBotonLugarPActionPerformed(evt);
            }
        });

        campoTextoPosicion.setEnabled(false);

        tiposDeVehiculos.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Automovil", "Camioneta", "Motocicleta", "Bicicleta", "Utilitario" }));

        jLabel1.setText("Tipo de Vehiculo");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(botonAceptar, javax.swing.GroupLayout.DEFAULT_SIZE, 114, Short.MAX_VALUE)
                                .addGap(75, 75, 75)
                                .addComponent(botonCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(labelDominio)
                                .addGap(18, 18, 18)
                                .addComponent(campoTextoDominio, javax.swing.GroupLayout.DEFAULT_SIZE, 185, Short.MAX_VALUE)))
                        .addGap(25, 25, 25))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(checkBotonLugarP)
                            .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 127, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(tiposDeVehiculos, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(campoTextoPosicion, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 176, Short.MAX_VALUE))
                        .addGap(26, 26, 26))))
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {botonAceptar, botonCancelar});

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {campoTextoDominio, campoTextoPosicion});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelDominio)
                    .addComponent(campoTextoDominio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tiposDeVehiculos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 7, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(checkBotonLugarP)
                    .addComponent(campoTextoPosicion, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(botonAceptar)
                    .addComponent(botonCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {botonAceptar, botonCancelar});

        layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {campoTextoDominio, campoTextoPosicion});

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void botonAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonAceptarActionPerformed
        manejadorCochera mc = new manejadorCochera(this.conexion);
        manejadorEstadia me = new manejadorEstadia(this.conexion);
        try {
            int capacidad = mc.getCantidad();
            int ocupados = 0;
            ResultSet auxiliar  = me.buscarEstadiaOcupado();
            int tipoV = tiposDeVehiculos.getSelectedIndex();
            while (auxiliar.next()){
                ocupados++;
            }
            if (ocupados < capacidad) {
                dominio = campoTextoDominio.getText().toUpperCase();
                manejadorVehiculo mv = new manejadorVehiculo(this.conexion);
                if (mv.esPatenteValida(dominio)) {
                    //evalua las condiciones que debe cumplir el campo dominio.
                    try {
                        if (!mv.buscarVehiculoPorDominio(this.dominio).next()) {
                            mv.insertarVehiculoSinCliente(this.dominio, "", "",tipoV);
                        }
                        int posicion = -1;
                        ResultSet lugares = me.obtenerPosicionesOcupados();
                        if (checkBotonLugarP.isSelected()){
                            if (!campoTextoPosicion.getText().equals("")){
                                int posAux = Integer.parseInt (campoTextoPosicion.getText());
                                if (me.hayLugarDisponible(lugares, posAux)  && posAux <= capacidad){
                                    posicion = posAux;
                                }
                            }
                        }
                        else{
                            posicion = me.calcularProximaPosicion(lugares, capacidad);
                        }
                        if (posicion > 0){
                            if (!(me.buscarEstadia(dominio).next())){
                                String fecha = me.calcularFecha();
                                String hora  = me.calcularHora();
                                me.marcarEntrada(fecha, hora, dominio, posicion, tipoV);
                                ResultSet vehiculoCliente = mv.buscarVehiculoPorDominioConCliente(this.dominio);
                                if (!vehiculoCliente.next()){
                                    JOptionPane.showMessageDialog(null, " El vehiculo con dominio:\"" + dominio + "\" ha sido cargado satisfactoriamente en el lugar Nro: "+posicion, "B&B - Insercion Satisfactoria", JOptionPane.INFORMATION_MESSAGE);
                                    Tickets ticket = new Tickets(conexion);
                                    ticket.imprimirTicketIngreso(fecha, hora, dominio, posicion);
                                }
                                else{
                                    String dni = vehiculoCliente.getString("dni_propietario");
                                    manejadorCliente mcl = new manejadorCliente(this.conexion);
                                    ResultSet cliente = mcl.buscarClientePorDni(dni);
                                    if (cliente.next()){
                                        String nombre = cliente.getString("nombre");
                                        String apellido = cliente.getString("apellido");
                                        JOptionPane.showMessageDialog(null, "Ingreso del cliente: \""+nombre+" "+apellido+"\"", "B&B - Insercion Satisfactoria", JOptionPane.INFORMATION_MESSAGE);
                                    }
                                    else{
                                        JOptionPane.showMessageDialog(null, " Error interno: ", "B&B - Insercion Fallida", JOptionPane.ERROR_MESSAGE);
                                    }
                                }
                                marcarIngreso.this.dispose();
                                sp.actualizarVistaEstadia();
                                sp.llenarCamposDeTexto();
                                sp.setVisible(true);
                            }
                            else {
                                JOptionPane.showMessageDialog(null, " El vehiculo ya se encuentra en la cochera." , "B&B -  Informe", JOptionPane.ERROR_MESSAGE);
                            }
                        }
                        else {
                            JOptionPane.showMessageDialog(null, " El lugar que desea ocupar no se encuentra disponible." , "B&B -  Informe", JOptionPane.ERROR_MESSAGE);
                        }
                    } catch (Exception ex) {
                        JOptionPane.showMessageDialog(null, " Error interno: " + ex, "B&B -  Insercion Fallida", JOptionPane.ERROR_MESSAGE);
                    }
                } else {
                    JOptionPane.showMessageDialog(null, " El formato del dominio ingresado es incorrecto. Formato correcto: 'ABC123' ", "B&B - Ingreso Fallido", JOptionPane.ERROR_MESSAGE);
                }
            }
            else {
                JOptionPane.showMessageDialog(null, " La Capacidad de la Cochera esta llena" , "B&B -  Informe", JOptionPane.WARNING_MESSAGE);
                 marcarIngreso.this.dispose();
            }
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, " Error interno: " + ex, "B&B -  Insercion Fallida", JOptionPane.ERROR_MESSAGE);
        }

}//GEN-LAST:event_botonAceptarActionPerformed

    private void botonCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonCancelarActionPerformed
        marcarIngreso.this.dispose();
    }//GEN-LAST:event_botonCancelarActionPerformed

    private void checkBotonLugarPActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkBotonLugarPActionPerformed
       if (checkBotonLugarP.isSelected()){
            campoTextoPosicion.setEnabled(true);
        }
        else{
            campoTextoPosicion.setEnabled(false);
        }
    }//GEN-LAST:event_checkBotonLugarPActionPerformed


    private void centrarJFrame(){
        Dimension pantalla = Toolkit.getDefaultToolkit().getScreenSize();
        Dimension frame =this.getSize();
        this.setLocation((pantalla.width-frame.width)/2, (pantalla.height-frame.height)/2);
    }


    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new marcarIngreso().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton botonAceptar;
    private javax.swing.JButton botonCancelar;
    private javax.swing.JTextField campoTextoDominio;
    private javax.swing.JTextField campoTextoPosicion;
    private javax.swing.JCheckBox checkBotonLugarP;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel labelDominio;
    private javax.swing.JComboBox tiposDeVehiculos;
    // End of variables declaration//GEN-END:variables

}
